// ==========================================================================
// gin-sns自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/service/module/favorite_service.go
// author：jon
// ==========================================================================
package module

import (
	"errors"
	"gin-sns/app/dao/module/favorite"
	"gin-sns/app/model"
	"gin-sns/app/model/constants"
	favoriteModel "gin-sns/app/model/module/favorite"
	"time"

	"github.com/gin-gonic/gin"

	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/page"
)

var FavoriteService = newFavoriteService()

func newFavoriteService() *favoriteService {
	return &favoriteService{}
}

type favoriteService struct {
}

//根据主键查询数据
func (s *favoriteService) SelectRecordById(id int64) (*favoriteModel.Entity, error) {
	return favorite.FavoriteDao.SelectById(id)
}

//
func (s *favoriteService) SelectRecordsIn(idarr []int64) ([]favoriteModel.Entity, error) {

	list, err := favorite.FavoriteDao.FindIn("id", idarr)
	if list != nil && len(list) > 0 {
		err = errors.New("not found")
		list = nil
	}
	return list, err
}

//根据主键删除数据
func (s *favoriteService) DeleteRecordById(id int64) bool {
	return favorite.FavoriteDao.DeleteById(id)
}

//批量删除数据记录
func (s *favoriteService) DeleteRecordByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := favorite.FavoriteDao.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//添加数据
func (s *favoriteService) AddSave(req *favoriteModel.AddReq, ctx *gin.Context) (int64, error) {
	var entity favoriteModel.Entity

	//entity.Id = req.Id
	entity.UserId = req.UserId
	entity.EntityType = req.EntityType
	entity.EntityId = req.EntityId
	entity.Status = req.Status
	entity.CreateTime = time.Now()
	//entity.CreateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user != nil {
	//	entity.CreateBy = user.LoginName
	//}

	_, err := favorite.FavoriteDao.Insert(&entity)
	return entity.Id, err
}

//修改数据
func (s *favoriteService) EditSave(req *favoriteModel.EditReq, ctx *gin.Context) (int64, error) {
	entity := &favoriteModel.Entity{Id: req.Id}
	ok, err := favorite.FavoriteDao.FindOne(entity)

	if err != nil {
		return 0, err
	}

	if !ok {
		return 0, errors.New("数据不存在")
	}

	entity.UserId = req.UserId
	entity.EntityType = req.EntityType
	entity.EntityId = req.EntityId
	entity.Status = req.Status
	//entity.UpdateTime = time.Now()
	//entity.UpdateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user == nil {
	//	entity.UpdateBy = user.LoginName
	//}

	return favorite.FavoriteDao.Update(entity)
}

//根据条件查询数据
func (s *favoriteService) SelectListAll(params *favoriteModel.SelectPageReq) ([]favoriteModel.Entity, error) {
	return favorite.FavoriteDao.SelectListAll(params)
}

//根据条件分页查询数据
func (s *favoriteService) SelectListByPage(params *favoriteModel.SelectPageReq) ([]favoriteModel.Entity, *page.Paging, error) {
	return favorite.FavoriteDao.SelectListByPage(params)
}

// 导出excel
func (s *favoriteService) Export(param *favoriteModel.SelectPageReq) (string, error) {
	head := []string{"", "用户id", "实体类型", "实体id", "0未审核 1正常状态 2审核未通过 3删除", "创建时间"}
	col := []string{"id", "user_id", "entity_type", "entity_id", "status", "create_time"}
	return favorite.FavoriteDao.SelectListExport(param, head, col)
}

func (s *favoriteService) GetBy(userId int64, entityType int, entityId int64) *favoriteModel.Entity {

	req := new(favoriteModel.SelectPageReq)
	req.UserId = userId
	req.EntityType = entityType
	req.EntityId = entityId

	list, err := favorite.FavoriteDao.SelectListAll(req)
	if err != nil || list == nil {
		return nil
	}

	return &list[0]
}

// 收藏文章
func (s *favoriteService) AddArticleFavorite(userId, articleId int64) error {
	article, _ := ArticleService.SelectRecordById(articleId)
	if article == nil || article.Status != model.ArticleStatusPublished {
		return errors.New("收藏的文章不存在")
	}
	if err := s.addFavorite(userId, constants.EntityTypeArticle, articleId); err != nil {
		return err
	}
	// 发送消息
	MessageService.SendArticleFavoriteMsg(articleId, userId)
	return nil
}

func (s *favoriteService) CancelArticleFavorite(userId, articleId int64) error {
	article, _ := ArticleService.SelectRecordById(articleId)
	if article == nil || article.Status != model.ArticleStatusPublished {
		return errors.New("收藏的文章不存在")
	}
	if err := s.cancelFavorite(userId, constants.EntityTypeArticle, articleId); err != nil {
		return err
	}
	// 发送消息
	//messageService.SendArticleFavoriteMsg(articleId, userId)
	return nil
}

// 收藏帖子
func (s *favoriteService) AddPostFavorite(userId, postId int64) error {
	post, _ := PostService.SelectRecordById(postId)
	if post == nil || post.Status != model.PostStatusOk {
		return errors.New("收藏的话题不存在")
	}

	if err := s.addFavorite(userId, constants.EntityTypePost, postId); err != nil {
		return err
	}

	// 发送消息
	MessageService.SendPostFavoriteMsg(postId, userId)
	return nil
}

func (s *favoriteService) CancelPostFavorite(userId, postId int64) error {
	post, _ := PostService.SelectRecordById(postId)
	if post == nil || post.Status != model.PostStatusOk {
		return errors.New("收藏的话题不存在")
	}

	if err := s.cancelFavorite(userId, constants.EntityTypePost, postId); err != nil {
		return err
	}

	// 发送消息
	//messageService.SendPostFavoriteMsg(postId, userId)
	return nil
}

func (s *favoriteService) addFavorite(userId int64, entityType int, entityId int64) error {
	temp := s.GetBy(userId, entityType, entityId)
	if temp != nil { // 已经收藏
		return nil
	}
	req := &favoriteModel.AddReq{
		UserId:     userId,
		EntityType: entityType,
		EntityId:   entityId,
		//CreateTime: time.Now(),
	}
	_, err := s.AddSave(req, nil)

	return err
}

func (s *favoriteService) cancelFavorite(userId int64, entityType int, entityId int64) error {
	entity := s.GetBy(userId, entityType, entityId)
	if entity != nil { // 已经收藏
		favorite.FavoriteDao.Delete(entity)
	}

	return nil
}
